<?php
/*
 * Created on Aug 30, 2012
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */

include_once("../admin/lib/domain/LinkDomain.php");
include_once("../admin/lib/domain/AdvertiserDomain.php");

class GoogleAffiliateApi
{
	private $cPublisherID   =   'K380716';
	private $cScope         =   'https://www.googleapis.com/auth/gan.readonly';
	private $cClientID      =   '126738922261.apps.googleusercontent.com';
	private $cClientSecret  =   'aT_kmncInPPNVCxEMidx5h58';
	private $cRedirectURI   =   'urn:ietf:wg:oauth:2.0:oob';
	 
	private $cAuthCode      =   '4/-glVsDkn__oT4wlRYiA-aXAYwLzx.0lZvj161EkgcuJJVnL49Cc9MKl_rcgI';
	private $cRefreshToken  =   '1/sSIZzjCPCOs5fjFeFgArKNYo4m35cyv-_rXKmqCi4Y8';
	private $cAccessToken;
	
	private $bRefresh = true;
	
	public function GoogleAffiliateApi()
	{
	}
	
	public function setClientId($cClientID)
	{
		$this->cClientID = $cClientID;
	}
	
	public function setClientSecret($cClientSecret)
	{
		$this->cClientSecret = $cClientSecret;
	}
	
	public function setRedirectURI($cRedirectURI)
	{
		$this->cRedirectURI = $cRedirectURI;
	}
	
	public function setAuthCode($cAuthCode)
	{
		$this->cAuthCode = $cAuthCode;
	}
	
	public function setRefreshToken($cRefreshToken)
	{
		$this->cRefreshToken = $cRefreshToken;
	}
	
	public function setScope($cScope)
	{
		$this->cScope = $cScope;
	}
	
	public function init()
	{
		if (empty($this->cAuthCode)) {
		    $rsParams = array(
		                        'response_type' =>   'code',
		                        'client_id'     =>   $this->cClientID,
		                        'redirect_uri'  =>   $this->cRedirectURI,
		                        'scope'         =>   $this->cScope
		                        );
		    $cOauthURL = 'https://accounts.google.com/o/oauth2/auth?' . http_build_query($rsParams);
		    echo("Go to\n$cOauthURL\nand enter the given value into \$cAuthCode\n");
		    exit();
		} elseif (empty($this->cRefreshToken)) {
		    $cTokenURL = 'https://accounts.google.com/o/oauth2/token';
		    $rsPostData = array(
		                        'code'          =>   $this->cAuthCode,
		                        'client_id'     =>   $this->cClientID,
		                        'client_secret' =>   $this->cClientSecret,
		                        'redirect_uri'  =>   $this->cRedirectURI,
		                        'grant_type'    =>   'authorization_code',
		                        );
		    $ch = curl_init();
		 
		    curl_setopt($ch, CURLOPT_URL, $cTokenURL);
		    curl_setopt($ch, CURLOPT_POST, 1);
		    curl_setopt($ch, CURLOPT_POSTFIELDS, $rsPostData);
		    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		 
		    $cTokenReturn = curl_exec($ch);
		    $oToken = json_decode($cTokenReturn);
		    echo("Enter the following values:\n\n");
		    echo("\$cRefreshToken = '" . $oToken->refresh_token . "';\n");
		}else{
			// Get a new Access Token
		    $cTokenURL = 'https://accounts.google.com/o/oauth2/token';
		    $rsPostData = array(
		                        'client_secret' =>   $this->cClientSecret,
		                        'grant_type'    =>   'refresh_token',
		                        'refresh_token' =>   $this->cRefreshToken,
		                        'client_id'     =>   $this->cClientID
		                        );
		    $ch = curl_init();
		 
		    curl_setopt($ch, CURLOPT_URL, $cTokenURL);
		    curl_setopt($ch, CURLOPT_POST, 1);
		    curl_setopt($ch, CURLOPT_POSTFIELDS, $rsPostData);
		    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		 
		    $cTokenReturn 	= curl_exec($ch);
		    $oToken 		= json_decode($cTokenReturn);
		    $this->cAccessToken 	= $oToken->access_token;
		}
	}
	
	private function getLinksJson($maxResults = 100, $pageCount = 1, $createDateMin = '', $createDateMax = '', $relationshipStatus = 'approved', $advertiserId = '', $authorship = 'advertiser', $linkType = '')
	{
	 	$arrJson = array();
	 	
	 	$pageCounter = 0;
	 	
	 	while (true) {
		    // Get the results
		    $cGANURL = 'https://www.googleapis.com/gan/v1beta1/publishers/' . $this->cPublisherID . '/links?';
		    
		    if(empty($maxResults) || $maxResults > 100){
		    	$cGANURL .= 'maxResults=100';
		    }else{
		    	$cGANURL .= 'maxResults=' . $maxResults;
		    }
		    
		    
		    if(!empty($createDateMin)){
		    	$cGANURL .= '&createDateMin=' . str_replace(" ", "T", $createDateMin) . 'Z';
		    }
		    
		    if(!empty($createDateMax)){
		    	$cGANURL .= '&createDateMax=' . str_replace(" ", "T", $createDateMax) . 'Z';
		    }
		    
		    if(!empty($relationshipStatus)){
		    	$cGANURL .= '&relationshipStatus=' . $relationshipStatus;
		    }
		    
		    if(!empty($advertiserId)){
		    	$cGANURL .= '&advertiserId=' . $advertiserId;
		    }
		    
		    if(!empty($authorship)){
		    	$cGANURL .= '&authorship=' . $authorship;
		    }
		    
		    if(!empty($linkType)){
		    	$cGANURL .= '&linkType=' . $linkType;
		    }
		    
		    if (isset($cJson->nextPageToken)) 
		 		$cGANURL .= '&pageToken=' . $cJson->nextPageToken;
	
			echo "GAN URL = $cGANURL";
			echo "\n";
			
		    $cAuthHeader = "Authorization: OAuth " . $this->cAccessToken;	 		
		 
		    $ch = curl_init();
		 
		    curl_setopt($ch, CURLOPT_HTTPHEADER, array($cAuthHeader));
		    curl_setopt($ch, CURLOPT_URL, $cGANURL);
		    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		 
		    $cJsonReturn 	= curl_exec($ch);	
		 	$cJson 			= json_decode($cJsonReturn);
		 	
		    $arrJson[] = $cJson;
		    
		    
		    $pageCounter++;
		    if($pageCounter >= $pageCount){
		    	echo "=============== page count: " . $pageCount;
		    	echo "\n";
		    	echo "=============== page counter: " . $pageCounter;
		    	echo "\n";
		    	
		    	break;
		    	
		    }
		    
		    
		    if (!isset($cJson->nextPageToken))
		 		break;	
		}
		
		return $arrJson;		
	}
	
	private function getAdvertiserJson($advertiserId)
	{
	    // Get the results
	    $cGANURL 		= 'https://www.googleapis.com/gan/v1beta1/publishers/' . $this->cPublisherID . '/advertiser?advertiserId='. $advertiserId;
	    
	    $cAuthHeader 	= "Authorization: OAuth " . $this->cAccessToken;	 		
	 
	    $ch = curl_init();
	 
	    curl_setopt($ch, CURLOPT_HTTPHEADER, array($cAuthHeader));
	    curl_setopt($ch, CURLOPT_URL, $cGANURL);
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	 
	    $cJsonReturn 	= curl_exec($ch);	
	 	$cJson 			= json_decode($cJsonReturn);	 	
	 	
		return $cJson;		
	}
	
	private function getAdvertisersJson($relationshipStatus = '', $advertiserCategory = '')
	{
	 	$arrJson 	= array();
	 	
	 	$limitPage 	= 0;
	 	$counter	= 0;
	 	
	 	while (true) {
		    // Get the results
		    $cGANURL = 'https://www.googleapis.com/gan/v1beta1/publishers/' . $this->cPublisherID . '/advertisers?maxResults=2';
		    
		    if(!empty($relationshipStatus)){
		    	$cGANURL .= '&relationshipStatus=' . $relationshipStatus;
		    }
		    
		    if(!empty($advertiserCategory)){
		    	$cGANURL .= '&advertiserCategory=' . $advertiserCategory;
		    }
		    
		    if (isset($cJson->nextPageToken)) 
		 		$cGANURL .= '&pageToken=' . $cJson->nextPageToken;
	
//			echo "\r";
//			echo "cGANURL = $cGANURL";
//			echo "\r";
			
		    $cAuthHeader = "Authorization: OAuth " . $this->cAccessToken;	 		
		 
		    $ch = curl_init();
		 
		    curl_setopt($ch, CURLOPT_HTTPHEADER, array($cAuthHeader));
		    curl_setopt($ch, CURLOPT_URL, $cGANURL);
		    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		 
		    $cJsonReturn 	= curl_exec($ch);	
		 	$cJson 			= json_decode($cJsonReturn);
		 	
		    $arrJson[] = $cJson;
		    
		    $counter++;
		    
		    if($counter > $limitPage)
		    	break;
		    		
		    if (!isset($cJson->nextPageToken))
		 		break;	
		}
		
		return $arrJson;		
	}
	
	public function getAdvertiser($advertiserId)
	{
		$stdObj 	= $this->getAdvertiserJson($advertiserId);
		$oItem 		= $stdObj->item;
		
		if(empty($oItem->name))
			return false;
			
		$oAdver 	= new AdvertiserDomain();
		
		$oAdver->setId($oItem->id);
		$oAdver->setName($oItem->name);
		$oAdver->setCategory($oItem->category);
		$oAdver->setStatus($oItem->status);
		$oAdver->setSiteUrl($oItem->siteUrl);
		$oAdver->setDescription($oItem->description);
		$oAdver->setProductFeedsEnabled($oItem->productFeedsEnabled);
		$oAdver->setCommissionDuration($oItem->commissionDuration);
		$oAdver->setLogoUrl($oItem->logoUrl);
		$oAdver->setContactEmail($oItem->contactEmail);
		$oAdver->setContactPhone($oItem->contactPhone);
		$oAdver->setPayoutRank($oItem->payoutRank);
		$oAdver->setJoinDate($oItem->joinDate);
		$oAdver->setAllowPublisherCreatedLinks($oItem->allowPublisherCreatedLinks);
		$oAdver->setDefaultLinkId($oItem->defaultLinkId);
		
		$oAdver->setEpcNinetyDayAverageAmount($oItem->epcNinetyDayAverage->amount);
		$oAdver->setEpcNinetyDayAverageCurrencyCode($oItem->epcNinetyDayAverage->currencyCode);
		
		$oAdver->setEpcSevenDayAverageAmount($oItem->epcSevenDayAverage->amount);
		$oAdver->setEpcSevenDayAverageCurrencyCode($oItem->epcSevenDayAverage->currencyCode);		
		
		return $oAdver; 
	}
	
	public function getAdvertisers($relationshipStatus = '', $advertiserCategory= '')
	{
		$arrJson = $this->getAdvertisersJson($relationshipStatus, $advertiserCategory);
		
		$advertisers 	= array();
		
		foreach($arrJson as $stdObj){
			if(isset($stdObj->items)){
				foreach($stdObj->items as $oItem){
					if(empty($oItem->name))
						continue;
								
					$oAdver = new AdvertiserDomain();
			
					$oAdver->setId($oItem->id);
					$oAdver->setName($oItem->name);
					$oAdver->setCategory($oItem->category);
					$oAdver->setStatus($oItem->status);
					$oAdver->setSiteUrl($oItem->siteUrl);
					$oAdver->setDescription($oItem->description);
					$oAdver->setProductFeedsEnabled($oItem->productFeedsEnabled);
					$oAdver->setCommissionDuration($oItem->commissionDuration);
					$oAdver->setLogoUrl($oItem->logoUrl);
					$oAdver->setContactEmail($oItem->contactEmail);
					$oAdver->setContactPhone($oItem->contactPhone);
					$oAdver->setPayoutRank($oItem->payoutRank);
					$oAdver->setJoinDate($oItem->joinDate);
					$oAdver->setAllowPublisherCreatedLinks($oItem->allowPublisherCreatedLinks);
					$oAdver->setDefaultLinkId($oItem->defaultLinkId);
					
					$oAdver->setEpcNinetyDayAverageAmount($oItem->epcNinetyDayAverage->amount);
					$oAdver->setEpcNinetyDayAverageCurrencyCode($oItem->epcNinetyDayAverage->currencyCode);
					
					$oAdver->setEpcSevenDayAverageAmount($oItem->epcSevenDayAverage->amount);
					$oAdver->setEpcSevenDayAverageCurrencyCode($oItem->epcSevenDayAverage->currencyCode);
					
					$advertisers[] = $oAdver;
				}
			}
		}
		
		return $advertisers;
	}
	
	public function getLinks($maxResults, $pageCount, $createDateMin = '', $createDateMax = '', $relationshipStatus = 'approved', $advertiserId = '', $linkType = '')
	{
		$arrJson 	= $this->getLinksJson($maxResults, $pageCount, $createDateMin, $createDateMax, $relationshipStatus, $advertiserId, 'advertiser', $linkType);
		$links 		= array();
		
		foreach($arrJson as $stdObj){
			if(isset($stdObj->items)){
				foreach($stdObj->items as $oItem){
					if(empty($oItem->name))
						continue;
					
					$link = new LinkDomain();
					
					$link->setId($oItem->id);
					$link->setName($oItem->name);
					
					$link->setKind($oItem->kind);
					$link->setIsActive($oItem->isActive);
					$link->setAdvertiserId($oItem->advertiserId);
					$link->setDestinationUrl($oItem->destinationUrl);
					$link->setLinkType($oItem->linkType);
					$link->setStartDate($oItem->startDate);
					$link->setEndDate($oItem->endDate);
					
					$link->setDescription($oItem->description);
					$link->setAvailability($oItem->availability);
					$link->setAuthorship($oItem->authorship);
					$link->setPromotionType($oItem->promotionType);
					$link->setDuration($oItem->duration);
					$link->setCreateDate($oItem->createDate);
					
					$link->setImpressionTrackingUrl($oItem->impressionTrackingUrl);
					$link->setClickTrackingUrl($oItem->clickTrackingUrl);
					
					$link->setEpcNinetyDayAverage($oItem->epcNinetyDayAverage);
					$link->setEpcSevenDayAverage($oItem->epcSevenDayAverage);
					$link->setSpecialOffers($oItem->specialOffers);
					
					$links[] = $link;
				}
			}
		}
		
		return $links;
	}
	
	
}
?>
